// deckManager.ts
import { FlipCard } from './interfaces';
import { Fruit, FunctionCardType, SpecialCardType } from './enums';

export class DeckManager {
  deck: FlipCard[] = [];
  discardPile: FlipCard[] = [];

  constructor() {
    this.initDeck();
    this.shuffleDeck();
  }

  initDeck(): void {
    // 添加水果牌: 每种7张
    for (let fruit = 1; fruit <= 5; fruit++) {
      for (let i = 0; i < 7; i++) {
        this.deck.push({ id: this.deck.length + 1, type: fruit });
      }
    }

    // 添加功能牌
    const functionCards = [
      { type: FunctionCardType.SquirrelGuidance, count: 3 },
      { type: FunctionCardType.StealHand, count: 6 },
      { type: FunctionCardType.Tornado, count: 2 },
      { type: FunctionCardType.OwlPeek, count: 4 }
    ];

    functionCards.forEach(card => {
      for (let i = 0; i < card.count; i++) {
        this.deck.push({ id: this.deck.length + 1, type: card.type });
      }
    });

    // 添加特殊牌
    for (let i = 0; i < 8; i++) {
      this.deck.push({ id: this.deck.length + 1, type: SpecialCardType.TigerRush });
    }
  }

  shuffleDeck(): void {
    for (let i = this.deck.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [this.deck[i], this.deck[j]] = [this.deck[j], this.deck[i]];
    }
  }

  drawCard(): FlipCard | null {
    if (this.deck.length === 0) {
      if (this.discardPile.length > 0) {
        this.reshuffleDiscardPile();
      } else {
        return null;
      }
    }
    return this.deck.pop() || null;
  }

  addToDiscard(card: FlipCard): void {
    this.discardPile.push(card);
  }

  reshuffleDiscardPile(): void {
    this.deck = [...this.discardPile];
    this.discardPile = [];
    this.shuffleDeck();
  }

  getDeckSize(): number {
    return this.deck.length;
  }

  getDiscardPileSize(): number {
    return this.discardPile.length;
  }
}